package org.wmq.positiontoshop.common;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.wmq.positiontoshop.model.DO.Shop;
import org.wmq.positiontoshop.model.ES.ShopES;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;

/**
 * Elasticsearch工具类
 * 提供ES相关的工具方法
 */
public class ElasticsearchUtils {
    
    /**
     * 将Shop DO对象转换为ShopES对象
     * 
     * @param shop Shop DO对象
     * @return ShopES对象
     */
    public static ShopES convertToShopES(Shop shop) {
        if (shop == null) {
            return null;
        }
        
        ShopES shopES = new ShopES();
        shopES.setId(shop.getId());
        shopES.setName(shop.getName());
        shopES.setDescription(shop.getDescription());
        
        // 设置地理位置
        if (shop.getLatitude() != null && shop.getLongitude() != null) {
            shopES.setLocation(new GeoPoint(shop.getLatitude(), shop.getLongitude()));
        }
        
        shopES.setAddress(shop.getAddress());
        shopES.setPhone(shop.getPhone());
        shopES.setBusinessHours(shop.getBusinessHours());
        shopES.setType(shop.getType());
        shopES.setRating(shop.getRating());
        shopES.setStatus(shop.getStatus());
        shopES.setCreateTime(shop.getCreateTime());
        shopES.setUpdateTime(shop.getUpdateTime());
        
        return shopES;
    }
    
    /**
     * 创建基础的Bool查询构建器
     * 
     * @param status 店铺状态（可选）
     * @return Bool查询构建器
     */
    public static BoolQueryBuilder createBaseBoolQueryBuilder(Integer status) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        
        // 如果有状态过滤
        if (status != null) {
            queryBuilder.filter(QueryBuilders.termQuery("status", status));
        }
        
        return queryBuilder;
    }
    
    /**
     * 向查询构建器添加排序规则
     * 
     * @param queryBuilder 查询构建器
     * @param sortBy 排序字段
     * @param sortOrder 排序顺序
     */
    public static void addSortToQueryBuilder(NativeSearchQueryBuilder queryBuilder, String sortBy, SortOrder sortOrder) {
        if (sortBy != null && !sortBy.isEmpty() && sortOrder != null) {
            queryBuilder.withSort(SortBuilders.fieldSort(sortBy).order(sortOrder));
        }
    }
    
    /**
     * 验证经纬度是否有效
     * 
     * @param latitude 纬度
     * @param longitude 经度
     * @return 是否有效
     */
    public static boolean isValidLocation(Double latitude, Double longitude) {
        return latitude != null && longitude != null && 
               latitude >= -90 && latitude <= 90 && 
               longitude >= -180 && longitude <= 180;
    }
}